package net.liuyimin.util;

import org.apache.zookeeper.*;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * Zookeeper客户端 : 负责获取链接和释放链接
 */
@Component //让Spring管理,当项目启动会扫描到当前类就会执行此类的无参构造方法
public class ZkClient {

    private static final String connectString = "127.0.0.1:2181";

    private static final String ROOT_PATH = "/distributed";

    private ZooKeeper zooKeeper;

    /**
     * 项目启动时初始化zk链接
     */
    @PostConstruct //在无参构造方法执行之后执行当前方法
    public void init() {
        // 获取链接,项目启动时初始化链接
        try {
            // 连接zookeeper服务器
            this.zooKeeper = new ZooKeeper(connectString, 30000, new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    System.out.println("获取链接成功！！");
                }
            });

            // 创建分布式锁根节点
            if (this.zooKeeper.exists(ROOT_PATH, false) == null){
                // 创建一个持久的节点
                this.zooKeeper.create(ROOT_PATH, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }
        } catch (Exception e) {
            System.out.println("获取链接失败！");
            e.printStackTrace();
        }
    }

    /**
     * 项目结束时释放zk链接
     */
    @PreDestroy //在Spring容器销毁之前执行当前方法
    public void destroy() {
        try {
            if (zooKeeper != null){
                zooKeeper.close();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化zk分布式锁对象方法
     *
     * @param lockName
     * @return
     */
    public ZkDistributedLock getZkDistributedLock(String lockName){
        // 本质是对zk的节点创建的争抢锁
        return new ZkDistributedLock(zooKeeper, lockName);
    }

}
